//
//  MSCreatProjectViewController.m
//  SocietySale
//
//  Created by Mike on 16/11/17.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MSCreatProjectViewController.h"
#import "MSCreatProjectTableVC.h"

@interface MSCreatProjectViewController ()<UIGestureRecognizerDelegate>
{
    NSString *proviceName;
    NSString *cityName;
    NSString *currentProviceStr;
    NSString *currentCityStr;
    NSString *currentStateStr;
    NSString *currentIndustryStr;
}
@property (nonatomic, strong) GXButton              *doneBtn;
@property (nonatomic, strong) UITextField           *investTextField;
@property (nonatomic, strong) SXTextView            *remarkTextView;
@property (nonatomic, assign) NSInteger             selectedRow;
@property (nonatomic, strong) NSMutableArray        *selectDataArray;
@property (nonatomic, strong) NSMutableArray        *selectStateArray;
@property (nonatomic, strong) MSDoubleListFilterVC              *areaFilterVC;       //地区筛选
@property (nonatomic, strong) MSFilterMultipleViewController   *areaSelectVC;
@property (nonatomic, strong) MSFilterMultipleViewController   *industrySelectVC;
@property (nonatomic, strong) MSFilterMultipleViewController   *stateSelectVC;
@property (nonatomic, strong) MSCreatProjectTableVC *tableVC;

@end

@implementation MSCreatProjectViewController

- (void)initNavigationBar{
    [super initNavigationBar];
    titleLable.text = @"创建项目";
    leftBarBtn.hidden = NO;
}

- (void)initUI{
    self.tableVC = [[MSCreatProjectTableVC alloc] initWithStyle:UITableViewStyleGrouped];
    self.tableVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-KNavBarHeight-45);
    self.tableVC.enableRefresh = NO;
    self.tableVC.enableRequest = NO;
    self.tableVC.delegate = (id)self;
    self.tableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableVC.view];
    
    self.areaSelectVC = [self creatFilterVC];
    self.areaSelectVC.dataArray = [@[@"东北",@"华北",@"华东",@"华南",@"华中",@"西南"] mutableCopy];
    self.areaSelectVC.stateArray = [self creatStateArrayWithArray:self.areaSelectVC.dataArray];

    self.industrySelectVC = [self creatFilterVC];
//    self.industrySelectVC.dataArray = [@[@"电力", @"能源矿产", @"冶金", @"化工医疗", @"轻纺食品", @"环保", @"市政公用", @"交通运输", @"机械电子", @"建筑", @"建材", @"农林水利", @"生态休闲旅游", @"其他"] mutableCopy];
//    self.industrySelectVC.stateArray = [self creatStateArrayWithArray:self.industrySelectVC.dataArray];
    
    self.stateSelectVC = [self creatFilterVC];
//    self.stateSelectVC.dataArray = [@[@"工程筹备", @"勘察设计", @"主体施工", @"设备安装", @"装饰装修", @"园林绿化", @"竣工测试"] mutableCopy];
//    self.stateSelectVC.stateArray = [self creatStateArrayWithArray:self.stateSelectVC.dataArray];
    
    [self fillFilterData];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150)];
    footerView.backgroundColor = kDefaultViewBackgroundColor;
    self.tableVC.tableView.tableFooterView = footerView;
    
//    UIView *horizonLineView =[[UIView alloc] initWithFrame:CGRectMake(0, 43.4, SCREEN_WIDTH, 0.6)];
//    horizonLineView.backgroundColor = kNormalGray;
//    [footerView addSubview:horizonLineView];
//
//    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
//    bgView.backgroundColor = [UIColor whiteColor];
//    [footerView addSubview:bgView];
//    
//    UILabel *leftlabel= [[UILabel alloc]initWithFrame:CGRectMake(12, 15, 60, 20)];
//    leftlabel.font = HeitiFont(14);
//    leftlabel.textColor = kLightBlackColor;
//    leftlabel.text = @"选择类型";
//    [bgView addSubview:leftlabel];
    
    self.remarkTextView = [[SXTextView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 90)];
    self.remarkTextView.font = HeitiFont(14);
    self.remarkTextView.placeholder = @" 请填写简介…";
    self.remarkTextView.delegate = (id)self;
    self.remarkTextView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:self.remarkTextView];
    
    self.doneBtn = [[GXButton alloc] initWithFrame:CGRectMake(0, self.tableVC.view.bottom, SCREEN_WIDTH, 45)];
    self.doneBtn.titleLabel.font = HeitiFont(16);
    [self.doneBtn setTitle:@"完成" forState:UIControlStateNormal];
    [self.doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.doneBtn.backgroundColor = kBlueColor;
    [self.doneBtn addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.doneBtn];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShownLogin:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiddenLogin:) name:UIKeyboardWillHideNotification object:nil];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    tapGesture.delegate = self;
    [self.contentView addGestureRecognizer:tapGesture];
    
    proviceName = @"";
    cityName = @"";
    currentProviceStr = @"";
    currentCityStr = @"";
    currentIndustryStr = @"";
    currentStateStr = @"";
}

- (MSFilterMultipleViewController *)creatFilterVC
{
    MSFilterMultipleViewController *VC = [[MSFilterMultipleViewController alloc] init];
    VC.delegate = (id<MSFilterMultipleDelegate>)self;
    VC.showConfirmBtn = NO;
    VC.isMultipleSelect = NO;
    return VC;
}

- (MSDoubleListFilterVC *)areaFilterVC
{
    if (!_areaFilterVC) {
        _areaFilterVC = [[MSDoubleListFilterVC alloc] init];
        _areaFilterVC.delegate=(id<MSDoubleListFilterVCDelegate>)self;
    }
    return _areaFilterVC;
}

- (void)fillFilterData{
    //省市
    NSMutableArray *tempDataArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *tempCodeArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSDictionary *dict in netEngine.provincesArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            NSArray *tempArray = [HDUtil checkArray:dict[@"citys"]];
            NSMutableArray *citysArray = [NSMutableArray arrayWithCapacity:0];
            NSMutableArray *citysCodeArray = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *provinceDict in tempArray) {
                if ([provinceDict isKindOfClass:[NSDictionary class]]){
                    [citysArray addObject:[HDUtil check:provinceDict[@"name"]]];
                    [citysCodeArray addObject:[HDUtil check:provinceDict[@"code"]]];
                }
            }
            NSDictionary *chinaDict = @{[HDUtil check:dict[@"name"]]:citysArray};
            NSDictionary *chinaCodeDict = @{[HDUtil check:dict[@"code"]]:citysCodeArray};
            [tempDataArray addObject:chinaDict];
            [tempCodeArray addObject:chinaCodeDict];
        }
    }
    self.areaFilterVC.codeArray = tempCodeArray;
    self.areaFilterVC.dataArray = tempDataArray;
    
    //行业
    NSMutableArray *titleArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *codeArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSDictionary *dict in netEngine.projectIndustryArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            [titleArray addObject:[HDUtil check:dict[@"name"]]];
            [codeArray addObject:[HDUtil check:dict[@"code"]]];
        }
    }
    
    self.industrySelectVC.dataArray = titleArray;
    self.industrySelectVC.stateArray = [self creatStateArrayWithArray:titleArray];
    
    //阶段
    NSMutableArray *titleArray2 = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *codeArray2 = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSDictionary *dict in netEngine.projectStateArray) {
        if ([dict isKindOfClass:[NSDictionary class]]) {
            [titleArray2 addObject:[HDUtil check:dict[@"name"]]];
            [codeArray2 addObject:[HDUtil check:dict[@"code"]]];
        }
    }
    self.stateSelectVC.dataArray = titleArray2;
    self.stateSelectVC.stateArray = [self creatStateArrayWithArray:titleArray2];
    
    self.selectDataArray = [[NSMutableArray alloc] initWithObjects:self.areaSelectVC.dataArray,self.industrySelectVC.dataArray,self.stateSelectVC.dataArray, nil];
    self.selectStateArray = [[NSMutableArray alloc] initWithObjects:self.areaSelectVC.stateArray,self.industrySelectVC.stateArray,self.stateSelectVC.stateArray, nil];
}

- (NSMutableArray *)creatStateArrayWithArray:(NSArray*)array{
    NSMutableArray *mutalArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i= 0; i<array.count; i++) {
        [mutalArray addObject:@"NO"];
    }
    return mutalArray;
}

- (void)testDataFunc{
    MSProjectModel *model = [[MSProjectModel alloc] init];
    model.title = @"上海浦东世和空港中心商业住房项目";
    model.projectType =  @"房地产";
    model.projectState =  @"主体施工";
    model.investment =  @"2亿";
    model.address =  @"上海";

    self.tableVC.dataArray = [NSMutableArray arrayWithArray
                                 :@[
                                    [DOKeyValue key:@"项目名称" value:[HDUtil check:_projectName] placeHolder:@"未填写"],
                                    [DOKeyValue key:@"项目区域" value:@"" placeHolder:@"未选择"],
                                    [DOKeyValue key:@"所属行业" value:@"" placeHolder:@"未选择"],
                                    [DOKeyValue key:@"项目阶段" value:@"" placeHolder:@"未选择"],
                                    [DOKeyValue key:@"投资金额" value:@"" placeHolder:@"未填写"],
                                    ]];
}

#pragma mark - getData
- (void)updateViewController:(NSNotification *)note
{
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"CreatProject"]) {
            DOKeyValue *keyvalue = self.tableVC.dataArray[0];
            [[NSNotificationCenter defaultCenter] postNotificationName:KSelectedProject object:self userInfo:@{keyvalue.value:responseDic[@"CreatProject"]}];
            
            NSArray* viewControllers = [HDUtil checkNilArray:[rootNavigation viewControllers]];
            for (int i =0; i<viewControllers.count; i++) {
                UIViewController *vc = viewControllers[i];
                if ([vc isKindOfClass:[MSReleaseTradeViewController class]]) {
                    [rootNavigation popToViewController:viewControllers[i] animated:YES];
                    return;
                }
            }
        }
    }
}

- (void)doneClick{
    NSArray *tipArray = @[@"请填写项目名称",@"请选择项目区域",@"请选择所属行业",@"请选择项目阶段",@"请填写投资金额"];
    for (int i = 0; i<self.tableVC.dataArray.count-1; i++) {
        DOKeyValue *keyvalue = self.tableVC.dataArray[i];
        if ([[keyvalue.value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){//全是空格
            [HDUtil showMessage:tipArray[i]];
            return;
        }
    }
    if ([[self.remarkTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){//全是空格
        [HDUtil showMessage:@"请填写简介"];
        return;
    }
    DOKeyValue *keyvalue = self.tableVC.dataArray[0];
    DOKeyValue *dataValue = self.tableVC.dataArray[4];
    NSDictionary *dict = @{
                           @"province":currentProviceStr,
                           @"city":currentCityStr,
                           @"industry":currentIndustryStr,
                           @"stage":currentStateStr,
                           @"name":keyvalue.value,
                           @"investment":dataValue.value,
                           @"summary":self.remarkTextView.text};
    [netEngine requestCreatProjectWithTarget:self.VctrID hudView:self.contentView params:dict];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    if (indexPath.row == 1) {
//        if ([self.areaSelectVC.view superview]){}
//        [self.areaSelectVC showInView:self.contentView];
        if ([self.areaFilterVC.view superview]){}
        [self.areaFilterVC showInBelowView];
    }
    if (indexPath.row == 2) {
        if ([self.industrySelectVC.view superview]){}
        [self.industrySelectVC showInView:self.contentView];
    }
    if (indexPath.row == 3) {
        if ([self.stateSelectVC.view superview]){}
        [self.stateSelectVC showInView:self.contentView];
    }
    _selectedRow = indexPath.row;
}

#pragma mark - MSDoubleListFilterVCDelegate
- (void)selectedAreaProviceCode:(NSDictionary *)proviceDict cityCode:(NSDictionary *)cityDict isTap:(BOOL)isTap{//地区
    if (isTap) {
        return;
    }
    NSString *tempName = [cityDict allKeys][0];
    if (tempName.length) {
        proviceName = [proviceDict allKeys][0];
        cityName = [cityDict allKeys][0];
        currentProviceStr = [proviceDict allValues][0];
        currentCityStr = [cityDict allValues][0];
    }
    else{
        proviceName = @"";
        cityName = @"";
        currentProviceStr = @"";
        currentCityStr = @"";
    }
    
    DOKeyValue *doKeyValue = self.tableVC.dataArray[_selectedRow];
    doKeyValue.value = cityName;
//    if (!cityName.length) {
//        doKeyValue.value = proviceName;
//    }
    [_tableVC.tableView reloadData];
}

#pragma mark - MSFilterMultipleDelegate
- (void)selectedFilter{
    NSMutableArray *relutArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *relutCodeArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *tempDataArray = self.selectDataArray[_selectedRow-1];
    NSMutableArray *tempDtateArray = self.selectStateArray[_selectedRow-1];
    
    NSArray *codeArray;
    if (_selectedRow == 2) {//行业
        codeArray = netEngine.projectIndustryArray;
    }
    if (_selectedRow == 3) {//阶段
        codeArray = netEngine.projectStateArray;
    }
    for (int i = 0; i< tempDtateArray.count; i++) {
        NSString *stateStr = tempDtateArray[i];
        if ([stateStr isEqualToString:@"YES"]) {
            [relutArray addObject:tempDataArray[i]];
            
            NSDictionary *dict = codeArray[i];
            [relutCodeArray addObject:[HDUtil check:dict[@"code"]]];
        }
    }
    if (_selectedRow == 2) {//行业
        currentIndustryStr = [relutCodeArray componentsJoinedByString:@","];
    }
    if (_selectedRow == 3) {//阶段
        currentStateStr = [relutCodeArray componentsJoinedByString:@","];
    }

    NSString *resultStr = [relutArray componentsJoinedByString:@"、"];
    resultStr = resultStr.length ? resultStr:@"";
    
    DOKeyValue *doKeyValue = self.tableVC.dataArray[_selectedRow];
    doKeyValue.value = resultStr;
    [_tableVC.tableView reloadData];
}

//键盘显示的时候的处理
- (void)keyboardWasShownLogin:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    _tableVC.tableView.height = SCREEN_HEIGHT-KNavBarHeight-kbSize.height;
}

//键盘消失的时候的处理
- (void)keyboardWillBeHiddenLogin:(NSNotification*)aNotification
{
    _tableVC.tableView.height = SCREEN_HEIGHT-KNavBarHeight-45;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view.superview isKindOfClass:[UITableViewCell class]]) {
        return NO;
    }
    else{
        return YES;
    }
}

- (void)tapClick{
    [self.view endEditing:YES];
}

@end
